#pragma once
#include <iostream>
#include <stdint.h>
#include <string>
#include <cstring>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/in.h>
#include <arpa/inet.h>

namespace Server
{
    using namespace std;
    static const int gnum = 1024;
    static const string defaultIp = "0.0.0.0"; // TODO

    typedef function<void(string, uint16_t, string)> func_t; // 客户端Ip  客户端端口号  正文内容
    class udpServer
    {
    private:
        /* data */
        int _sockFd;
        string _Ip;
        uint16_t _port;
        func_t _callBack;

    public:
        udpServer(const uint16_t &port, const func_t &cb, const string &ip = defaultIp)
            : _Ip(ip), _port(port), _callBack(cb), _sockFd(-1)
        {
        }
        ~udpServer() {}

    public:
        void initServer()
        {
            _sockFd = socket(AF_INET, SOCK_DGRAM, 0);

            struct sockaddr_in local;
            bzero(&local, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_addr.s_addr = inet_addr(_Ip.c_str());
            local.sin_port = htons(_port);
            // local.sin_addr.s_addr = htonl(INADDR_ANY); // 任意地址bind，服务器的真实写法
            int n = bind(_sockFd, (struct sockaddr *)&local, sizeof(local));

            if (n == -1)
            {
                cerr << "bind error: " << errno << " : " << strerror(errno) << endl;
                exit(-1);
            }
        }
        void start()
        {
            // string buffer;
            //buffer.reserve(gnum);
            char buffer[gnum];     
            for (;;)
            {

                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                // ssize_t s = recvfrom(_sockFd,(void*)buffer.c_str(),buffer.size() - 1,0,(struct sockaddr*)&peer,&len);
                ssize_t s = recvfrom(_sockFd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
                if (s > 0) // 有客户端发消息了
                {
                    string clientIp = inet_ntoa(peer.sin_addr);
                    uint16_t clientPort = ntohs(peer.sin_port);
                    cout << clientIp << "[" << clientPort << "]# " << buffer << endl;
                    _callBack(clientIp, clientPort, buffer);
                }
            }
        }
    };

}
